
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 *
 * @author javauser
 */

//class handles backup operations
public class DataBackup 
{
    private String osslash=null;
    //method to zip files and logs before backup operations...
    public boolean  zipFile(String fileName, String filePath , String fileExtension,String configPath) 
    {
        if(OSDetector.isWindows())
        {
            osslash="\\";
        }
        if(OSDetector.isUnix())
        {
            osslash="/";
        }
        boolean check=true;
        byte[] buffer = new byte[1024];
        try
        {
            File fcheck=new File(filePath+osslash+fileName);
            if(fcheck.isDirectory())
            {
                System.out.println("this is a directory");
                try
                {
                    File inFolder=new File(fcheck.getPath());
                    File outFolder=new File(fcheck.getPath()+".zip");
                    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
                    BufferedInputStream in = null;
                    byte[] data    = new byte[1024];
                    String files[] = inFolder.list();
                    for (int i=0; i<files.length; i++)
                    {
                        in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + File.separator + files[i]), 1000);                 
                        out.putNextEntry(new ZipEntry(files[i])); 
                        int count;
                        while((count = in.read(data,0,1024)) != -1)
                        {
                            out.write(data, 0, count);
                        }
                        out.closeEntry();
                    }
                    out.flush();
                    out.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                } 
            }
            if(!fcheck.isDirectory())
            {
                System.out.println("this is a file...");
                FileOutputStream fos = new FileOutputStream(fcheck.getPath()+".zip");
                ZipOutputStream zos = new ZipOutputStream(fos);
                ZipEntry ze= new ZipEntry(fileName+"."+fileExtension);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(fcheck.getPath()+"."+fileExtension);
                int len;
                while ((len = in.read(buffer)) > 0) 
                {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
                zos.close();  
            }
            System.out.println("Done"); 
    	}
        catch(IOException ex)
        {
            check=false;
            new LogFile("System", " encountered the following Exception while trying to ZIP the file "+fileName+" and this is the error "+ex.getMessage(),configPath ); 
            //LogFile.log(" System ", " encountered the following Exception while trying to ZIP the file "+fileName+" and this is the error "+ex.getMessage());
            ex.printStackTrace();
    	} 
        return check;
     }
    
    //method to zip log files
     public boolean zipLog(String fileName, String filePath , String fileExtension) 
    {
        if(OSDetector.isWindows())
        {
            osslash="\\";
        }
        if(OSDetector.isUnix())
        {
            osslash="/";
        }
        boolean check=true;
        byte[] buffer = new byte[1024];
        try
        {
            File fcheck=new File(filePath+osslash+fileName);
            if(fcheck.isDirectory())
            {
                try
                {
                    File inFolder=new File(fcheck.getPath());
                    File outFolder=new File(fcheck.getPath()+".zip");
                    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
                    BufferedInputStream in = null;
                    byte[] data    = new byte[1024];
                    String files[] = inFolder.list();
                    for (int i=0; i<files.length; i++)
                    {
                        in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + File.separator + files[i]), 1000);                 
                        out.putNextEntry(new ZipEntry(files[i])); 
                        int count;
                        while((count = in.read(data,0,1024)) != -1)
                        {
                            out.write(data, 0, count);
                        }
                        out.closeEntry();
                    }
                    out.flush();
                    out.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                } 
            }
            if(!fcheck.isDirectory())
            {
                System.out.println("this is a file...");
                FileOutputStream fos = new FileOutputStream(fcheck.getPath()+".zip");
                ZipOutputStream zos = new ZipOutputStream(fos);
                ZipEntry ze= new ZipEntry(fileName+fileExtension);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(fcheck.getPath()+fileExtension);
                int len;
                while ((len = in.read(buffer)) > 0) 
                {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
                zos.close();  
            }
            System.out.println("Done"); 
    	}
        catch(IOException ex)
        {
            check=false;
            LogFile.log(" System ", " encountered the following problem while trying to take backup from log files with date "+fileName+" and this is the problem "+ex.getMessage());
            ex.printStackTrace();
    	} 
        return check;
     }
    //method to upload Provider file on ftp server
    public boolean upLoadFile(String ftpHostName, String filedirectory, String ftpUsername, String ftpPassword , String fileName) 
    {
        boolean check=true;
        System.out.println("Hello i am inside Upload Method");
        FTPClient client = new FTPClient();
        FileInputStream fis = null;
        try 
        {
            client.connect(ftpHostName);
            client.login(ftpUsername,ftpPassword);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            if(client.login(ftpUsername,ftpPassword))
            {
                check=true;
                System.out.println("I Logged in Already....");
                int reply = client.getReplyCode();
                if(FTPReply.isPositiveCompletion(reply))
                {
                    System.out.println("Connected Success");
                    File myFile=new File(filedirectory);
                    fis = new FileInputStream(myFile);
                    client.storeFile(fileName, fis);
                    client.logout();
   }
            }
            else
            {
                check=false;
                System.out.println("Sorry Can not login ....");
            }
            //
            // Create an InputStream of the file to be uploaded
            //
        } 
        catch (IOException e) 
        {
            check=false;
            e.printStackTrace();
            //LogFile.log(" System "," failed to  login to ftp server due to the following reason "+e.getMessage());
        } 
        finally 
        {
            try 
            {
                if (fis != null) 
                {
                    fis.close();
                }
                client.disconnect();
            } 
            catch (IOException e) 
            {
                check=false;
                LogFile.log(" System "," failed to disconnect from the Connection with the ftp server due to the following reason "+e.getMessage());
                e.printStackTrace();
            }
        }
        return check;
    }
    
    //method to upload Log Files to ftp Server
    public boolean upLoadLog(String ftpHostName, String filedirectory, String ftpUsername, String ftpPassword , String fileName) 
    {
        boolean check=true;
        System.out.println("Hello i am inside Upload Method");
        FTPClient client = new FTPClient();
        FileInputStream fis = null;
        try 
        {
            client.connect(ftpHostName);
            client.login(ftpUsername,ftpPassword);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            if(client.login(ftpUsername,ftpPassword))
            {
                check=true;
                System.out.println("I Logged in Already....");
                int reply = client.getReplyCode();
                if(FTPReply.isPositiveCompletion(reply))
                {
                    System.out.println("Connected Success");
                    File myFile=new File(filedirectory);
                    fis = new FileInputStream(myFile);
                    client.storeFile(fileName, fis);
                    client.logout();
   }
            }
            else
            {
                check=false;
                System.out.println("Sorry Can not login ....");
            }
            //
            // Create an InputStream of the file to be uploaded
            //
        } 
        catch (IOException e) 
        {
            check=false;
            e.printStackTrace();
            LogFile.log(" System "," failed to  login to ftp server due to the following reason "+e.getMessage());
        } 
        finally 
        {
            try 
            {
                if (fis != null) 
                {
                    fis.close();
                }
                client.disconnect();
            } 
            catch (IOException e) 
            {
                check=false;
                LogFile.log(" System "," failed to disconnect from the Connection with the ftp server due to the following reason "+e.getMessage());
                e.printStackTrace();
            }
        }
        return check;
    }
    
    //test
    public static void main(String args[])
    {
        //DataBackup db=new DataBackup();
        //db.upLoadFile("172.16.4.23", "/home/ahmed/SupplierFiles/centersoft.zip", "A7med Kotb", "1837895123asikkisa", "centersoft.zip");
        //db.zipFile("alan", "/home/ahmed/SupplierFiles", "txt");
    }
}
